package cn.edu.zhku.citrusmonitor.person.user.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSON;

import cn.edu.zhku.citrusmonitor.domain.TbUser;
import cn.edu.zhku.citrusmonitor.person.user.service.UserService;
import cn.edu.zhku.citrusmonitor.person.user.service.UserServiceImpl;
import cn.edu.zhku.citrusmonitor.person.util.Message;
import cn.edu.zhku.citrusmonitor.person.util.PageBean;
import cn.edu.zhku.citrusmonitor.person.util.RandomColor;
import cn.edu.zhku.citrusmonitor.util.BaseServlet;

@WebServlet("/user.do")
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	UserService us=new UserServiceImpl();
	/**
	 * 登陆(专家，管理员，普通用户)
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> m=new HashMap<String,String[]>();
		m=request.getParameterMap();
		TbUser user=new TbUser();
		System.out.print(request.getSession().getAttribute("checkedCode")+" sessionck="+m.get("checkedCode")[0]);
		if(request.getSession().getAttribute("checkedCode").equals(m.get("checkedCode")[0])) {
			String phone=m.get("phone")[0];
			String password=m.get("password")[0];
			if(us.searchByPhone(phone)!=null) {
				if((user=us.login(phone,password))!=null) {
					//用户放入session当中 
					System.out.print(JSON.toJSONString(new Message("1","登陆成功")));
					
					request.getSession().setAttribute("user",user);               //放入session当中，以便于修改信息时取出id
					//System.out.println((TbUser)request.getSession().getAttribute("user"));
					//request.getRequestDispatcher("/modify.html").forward(request, response);;
					return JSON.toJSONString(new Message("1","登陆成功",phone));
				}else
					return JSON.toJSONString(new Message("2","用户名或密码错误"));
			}else
				//System.out.print(JSON.toJSONString(new Message("2","此用户不存在")));
				return JSON.toJSONString(new Message("2","此用户不存在"));
		}else {
			//JSONObject.fromObject(object);
			System.out.print(JSON.toJSONString(new Message("2","验证码错误")));
			return JSON.toJSONString(new Message("2","验证码错误")); 
		}
	}
	/**
	 * 用户注册(成功返回status：1，失败为2)
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalAccessException, InvocationTargetException {
		TbUser user=new TbUser();
		BeanUtils.populate(user, request.getParameterMap());
		user.setUserId(UUID.randomUUID().toString());
		//List<Message> l=new ArrayList<>();
		//l.add(new Message("1","heh"));
		//l.add(new Message("3","xiix"));
		if(us.addUser(user).equals("success")) {		//return 1 for success,2 for failure
			//JSONObject.fromObject(object);
			//System.out.println(JSON.toJSONString(l));
			return JSON.toJSONString(new Message("1","register successfully!"));//alibaba json  
		}else {
			return JSON.toJSONString(new Message("2","registration failed!"));
		}
	}
	/**
	 * 获得验证码图片
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void checkImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
		if(request.getSession().getAttribute("words")==null) {     //判断是否第一次进入此页面
			List<String> words=new ArrayList<>();
			String path=request.getServletContext().getRealPath("/WEB-INF/new_words.txt");//获取验证码文字
			//读取每一行文字
			BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
			String line;
			while((line=br.readLine())!=null) {
				words.add(line);
			}
			//存入session中
			//System.out.print("a"+words.get(1));
			request.getSession().setAttribute("words", words);
		}
		
		//draw a picture in 120 width,30 height
		List<String> words=(List<String>)request.getSession().getAttribute("words");
		//System.out.print("0out"+words.get(1));
		int width=120;
		int height=30;
		BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics graphics=img.getGraphics();
		//get random color from 100 to 180
		graphics.setColor(RandomColor.getRandColor(200, 250));
		//fill its background-color
		graphics.fillRect(0, 0, width, height);
		graphics.setColor(Color.white);
		//draw its rect
		graphics.drawRect(0, 0, width-1, height-1);
		Graphics2D graphics2d=(Graphics2D)graphics;
		graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
		Random random=new Random();
		String word=words.get(random.nextInt(words.size()));
		int x=10;
		//write words
		for(int i=0;i<word.length();i++) {
			//a random color of a word
			graphics2d.setColor(RandomColor.getRandColor(80, 150));
			int angle=random.nextInt(60)-30;
			double theta= angle*Math.PI/180;
			graphics2d.rotate(theta,x,20);
			char c=word.charAt(i);
			graphics2d.drawString(String.valueOf(c), x, 20);
			graphics2d.rotate(-theta,x,20);
			x+=30;
		}
		request.getSession().setAttribute("checkedCode", word);
		//add disturbing string
		graphics2d.setColor(RandomColor.getRandColor(120, 180));
		for(int i=0;i<30;i++) {
			int x1=random.nextInt(width);
			int y1=random.nextInt(height);
			int x2=random.nextInt(12);
			int y2=random.nextInt(12);
			graphics2d.drawLine(x1, y1, x1+x2, x2+y2);
		}	
		graphics2d.dispose();
		graphics.dispose();
		ImageIO.write(img, "jpg",response.getOutputStream());
	}
	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @return
	 */
	/*public String page(HttpServletRequest request,HttpServletResponse response) {
		String currentPage="1";//默认为1
		if(request.getParameter("currentPage")!=null) {
			currentPage=request.getParameter("currentPage");
		}
		PageBean<TbUser> pb=new PageBean<TbUser>();
		long pageSize=pb.getPageSize();
		long totalCount=us.getTotalCounts();//总记录数
		//获取包含该页的所有对象的集合
		pb.setBeanList(us.getBeanList(Integer.parseInt(currentPage),pageSize));
		pb.setCurrentPage(Integer.parseInt(currentPage));
		pb.setCount(totalCount);
		System.out.println(JSON.toJSONString(pb));
		
		return JSON.toJSONString(pb);
	}*/
	/**
	 * 修改用户信息(个人修改以及管理员修改)
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public String modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalAccessException, InvocationTargetException {
		TbUser user=new TbUser();
		//无论是管理员后台修改还是用户个人信息修改先获取id，若有id再覆盖
		user=(TbUser)request.getSession().getAttribute("user");
		//user.setUserId((TbUser)request.getSession().getAttribute("user"));
		if(user==null) {
			user=new TbUser();
			BeanUtils.populate(user,request.getParameterMap());
		}
		//String id=us.getUserId(user);
		//System.out.println(user);
		if(us.modifyUser(user)!=0) {
			System.out.print(JSON.toJSONString(new Message("1","修改信息成功",user.getUserId())));
			return JSON.toJSONString(new Message("1","修改信息成功",user.getUserId()));
		}else
			return JSON.toJSONString(new Message("2","修改失败"));
		
	}
	/**
	 * 根据id删除用户
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("userId");
		
		if(us.deleteUser(id)!=0) {
			return JSON.toJSONString(new Message("1","删除用户成功"));
		}else
			return JSON.toJSONString(new Message("2","删除用户失败"));
			
	}	
	/**
	 * 根据手机查找用户（模糊查询）
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findUserByPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phone=request.getParameter("phone");
		List<TbUser> list=new ArrayList<TbUser>();
		if((list=us.getUserByPhone(phone))!=null) {
			System.out.println(JSON.toJSONString(list));
			return JSON.toJSONString(list);
		}else
			return JSON.toJSONString(new Message("2","查找失败"));
	}
	/**
	 * 根据id查找用户
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findUserById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("userId");
		TbUser user=new TbUser();
		if((user=us.getUser(id))!=null&&id!=null&&!id.equals("")) {
			return JSON.toJSONString(user);
		}else
			return JSON.toJSONString(new Message("2","查找用户失败"));
	}
	/**
	 * 分页查找
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String currentPage="1";//默认为1
		if(request.getParameter("currentPage")!=null) {
			currentPage=request.getParameter("currentPage");
		}
		PageBean<TbUser> pb=new PageBean<TbUser>();
		long pageSize=pb.getPageSize();
		long totalCount=us.getTotalCounts();//总记录数
		//获取包含该页的所有对象的集合
		pb.setBeanList(us.getBeanList(Integer.parseInt(currentPage),pageSize));
		pb.setCurrentPage(Integer.parseInt(currentPage));
		pb.setCount(totalCount);
		System.out.println(JSON.toJSONString(pb));
		
		return JSON.toJSONString(pb);
	}
	/**
	 * 检查用户是否存在
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String checkPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phone=request.getParameter("phone");
		TbUser user;
		if((user=us.searchByPhone(phone))!=null) {
			return JSON.toJSONString(user);
		}else
			return JSON.toJSONString(new Message("2","此用户不存在",phone));
			
	}
	/**
	 * 批量删除
	 * @param request
	 * @param response
	 * @return
	 */
	public String removeAll(HttpServletRequest request,HttpServletResponse response) { 
		String id=request.getParameter("ids");
		//System.out.println("id="+id);
		String[] ids=id.split(",");
	//	System.out.println("ids="+Arrays.toString(ids));
		if(ids==null||ids.length==0) {
			return JSON.toJSONString(new Message("2","获取复选框失败"));
		}
		if(ids.length==us.removeAll(ids)) {	
			//System.out.println("aaaaaaaaaaaaaaaa");
			return JSON.toJSONString(new Message("1","批量删除成功"));
		}else
			return JSON.toJSONString(new Message("2","批量删除失败"));
	
		
	}
	
}
